const path = require('path')
const query = require('../model/query.js')
const md5 = require('md5')
const { password_secret } = require('../config/config.js')


const controller = {}

//首页
controller.index = async (req, res) => {
    res.render('index.html')
}



//登录页面
controller.login = async (req, res) => {
    res.render('login.html')
}
//分类列表
controller.category = (req, res) => {
    res.render('category.html')
}
//文章列表
controller.article = (req, res) => {
    res.render('article.html')
}

//分类列表渲染数据
controller.cartData = async (req, res) => {
    let sql = `select * from car_class`
    let data = await query(sql)
    res.json({
        data,
        code: 0,
        // count:100,
        msg: 'success'
    }
    )
}
//编辑分类列表
controller.updcartData = async (req, res) => {
    let { cate_id, cate_name, orderBy } = req.body
    let sql = `update car_class set cate_name = '${cate_name}', orderBy = '${orderBy}' where cate_id = ${cate_id}`
    console.log(sql);
    let { affectedRows } = await query(sql)
    let succData = {
        code: 0,
        message: '编辑成功'
    }
    let responseData = {
        code: 1,
        message: '编辑失败'
    }
    if (affectedRows > 0) {
        res.json(succData)
    } else {
        res.json(responseData)
    }
}

//删除列表行
controller.delCart = async (req, res) => {
    let { cate_id } = req.body
    let sql = `delete from car_class where cate_id = ${cate_id}`
    let { affectedRows } = await query(sql)
    let succdel = {
        code: 0,
        message: '删除成功'
    }
    let responsedel = {
        code: 1,
        message: '编辑失败'
    }
    if (affectedRows > 0) {
        res.json(succdel)
    } else {
        res.json(responsedel)
    }
}

//后台名称
controller.loginGet = async (req, res) => {
    let sql = `select * from loginText`
    let rows = await query(sql)
    res.json(rows)
}

//请求登录
controller.userLogin = async (req, res) => {
    //1. 接受参数
    let {
        username,
        password
    } = req.body;
    //2. 拼接sql语句，查询用户名和密码是否匹配
    password = md5(`${password} ${password_secret}`)
    console.log(password);
    const sql = `select * from users where username = '${username}' and password = '${password}'`
    console.log(sql);
    //3. 成功，
    const result = await query(sql)
    console.log(result);
    if (result.length > 0) {

        // 将信息记录到session
        req.session.userInfo = result[0];
        res.cookie('userInfo', JSON.stringify(result[0]), {
            expires: new Date(Date.now() + 1 * 3600000),
        })
        res.json({
            code: 0,
            message: "登录成功"
        })
    } else {
        // 失败则提示用户
        res.json({
            code: -2,
            message: "登录失败"
        })
    }

}

//退出登录

controller.userLoginout = (req, res) => {
    //1. 清除session
    req.session.destroy(function (err) {
        if (err) {
            throw err;
        }

    })
    //2. 响应json
    res.json({
        code: 0,
        message: "logout success"
    })

}
module.exports = controller